package com.sz.app.customer.web.security;

import com.sz.biz.app.web.security.AbstractUserRealm;
import com.sz.biz.app.web.security.MyAuthenticationInfo;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.common.base.constants.AppDomain;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
 */
public class CustomerUserRealm extends AbstractUserRealm {

    @Autowired
    CustomerUserService customerUserService;
    @Autowired
    CustomerService customerService;

    /**
     * 验证当前登录的Subject
     * LoginController.login()方法中执行Subject.login()时 执行此方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        System.out.println("###【开始认证[SessionId]】" + SecurityUtils.getSubject().getSession().getId());

        String loginName = (String) authcToken.getPrincipal();
        CusUser user = customerUserService.findByAccountName(loginName);
        if (user == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        MyAuthenticationInfo authenticationInfo = new MyAuthenticationInfo(
                AppDomain.CUSTOMER,
                user.getId(),
                user.getUserName(), //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getCredentialSalt()),//salt=username+salt,采用明文访问时，不需要此句
                getName()  //realm name
        );
        return authenticationInfo;
    }
}

